package com.yellowframework.cloud.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

public class Oauth2Utils {

    public static UserJwt getUserJwtFromHeader() {
        return getUserJwtFromHeader(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
    }

    public static Map<String, String> getUserDetailsFromHeader(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        //取出头信息
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization) || !authorization.contains("Bearer")) {
            return null;
        }
        //从Bearer 后边开始取出token
        String token = authorization.substring(7);
        Map<String,String> map = null;
        try {
            //解析jwt
            Jwt decode = JwtHelper.decode(token);
            //得到 jwt中的用户信息
            String claims = decode.getClaims();
            //将jwt转为Map
            map = JSON.parseObject(claims, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static UserJwt getUserJwtFromHeader(HttpServletRequest request) {
        return JSON.parseObject(JSON.toJSONString(getUserDetailsFromHeader(request)), UserJwt.class);
    }

    public static Set<String> getUserPermissionsFromHeader(HttpServletRequest request) {
        final Map<String, String> details = getUserDetailsFromHeader(request);
        return new HashSet<>(JSON.parseArray(JSON.toJSONString(details.get("authorities")), String.class));
    }

    public static String getCurrentUsername(){
        return getCurrentUsername(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
    }

    public static String getCurrentUsername(HttpServletRequest request){
        return Optional.ofNullable(getUserJwtFromHeader(request)).orElse(new UserJwt()).getUsername();
    }

    @Data
    public static class UserJwt {
        private Integer id;

        private String username;

        private String password;

        private String name;

        private Set<String> roles;
    }
}
